package game.http;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpMethodDemo {
	
	public static void main(String[] args) {
		String path = "http://localhost:8080/game/HttpServer";
		String result = "";
		try {
			result = httpPost(path);
			System.out.println(result);
			result = httpGet(path);
			System.out.println(result);
		}catch (Exception e) {
			// TODO: handle exception
		}
	}

	private static String httpGet(String path) throws IOException {
		URL url = new URL(path + "?param1=firmye1&param2=firmye2");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.connect();
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		StringBuffer sBuffer = new StringBuffer();
		String line = "";
		while(null != (line = reader.readLine())) {
			sBuffer.append(line).append("\r\n");
		}
		reader.close();
		return sBuffer.toString();
	}

	private static String httpPost(String path) throws IOException {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.connect();
		
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
		writer.write("param1=firmye1&param2=firmye2");
		writer.close();
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		StringBuffer sBuffer = new StringBuffer();
		String line = "";
		while(null != (line = reader.readLine())) {
			sBuffer.append(line).append("\r\n");
		}
		reader.close();
		return sBuffer.toString();
	}

}
